<template>
  <xr-create
    :loading="loading"
    :title="title"
    :confirm-button-text="sureBtnTitle"
    :show-confirm="config.showConfirm"
    :show-cancel="config.showCancel"
    @close="close"
    @save="saveClick">
    <i
      slot="title-append"
      class="wk wk-icon-fill-help wk-help-tips"
      data-type="11"
      data-id="38" />
    <create-sections
      :title="$t('crm.contract.a7a95c3fbcc76050b56de8002ed95ea2')">
      <el-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :validate-on-rule-change="false"
        class="wk-form"
        label-position="top">
        <wk-form-items
          v-for="(children, index) in fieldList"
          :key="index"
          :field-from="fieldForm"
          :field-list="children"
          @change="formChange">
          <template slot-scope="{ data }">
            <crm-relative-cell
              v-if="data && data.formType == 'customer'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              data-type="customer"
              @value-change="otherChange($event, data)"
            />
            <crm-relative-cell
              v-if="data && (data.formType == 'business' || data.formType == 'contacts')"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              :props="data.props"
              :data-type="data.formType"
              @value-change="otherChange($event, data)"
            />
            <xh-product
              v-if="data && data.formType == 'product'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              @value-change="otherChange($event, data)"
            />
          </template>
        </wk-form-items>
      </el-form>
    </create-sections>

    <!-- <create-sections
      v-if="wkFlowList"
      :title="$t('crm.contract.a2b605ed2198d662511995eb54bd8f6f')">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-approval-flow-apply
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :is-edit="examineInfo.hasOwnProperty('examineStatus') && examineInfo.examineStatus == 2"
        :carbon-copy-edit-auth="carbonCopyEditAuth"
        :examine-advanced-setting="examineAdvancedSetting"
        style="padding: 15px;"
      />
    </create-sections> -->
    <create-sections
      v-if="wkFlowList"
      title="审核信息">
      <template slot="header">
        <el-tooltip
          v-if="flowRemarks"
          :content="flowRemarks"
          effect="dark"
          placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;" />
        </el-tooltip>
      </template>
      <wk-af-new-apply
        ref="afNewApply"
        :data="wkFlowList"
        :approver-edit-auth="approverEditAuth"
        :detail="examineAdvancedSetting"
        style="padding: 15px;" />
    </create-sections>

    <el-button
      v-if="!config.getFields"
      slot="footer"
      type="primary"
      plain
      @click.native="debouncedSaveField(true)">{{ $t('crm.contract.fc5253b82b0a89cadda2c8fa74cf2ce7') }}</el-button>

    <template slot="footer-left">
      <slot name="footer" />
    </template>
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from '@/api/crm/common'
import { crmContractSaveAPI } from '@/api/crm/contract'
import { crmBusinessProductAPI } from '@/api/crm/business'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'
import {
  CrmRelativeCell
} from '@/components/CreateCom'
// import WkApprovalFlowApply from '@/components/Examine/WkApprovalFlowApply'
import WkApprovalFlowApplyMixin from '@/components/Examine/mixins/WkApprovalFlowApply'
import WkAfNewApply from '@/components/Examine/WkAfNewApply'

import crmTypeModel from '@/views/crm/model/crmTypeModel'
import tagProps from '@/views/crm/model/tagDefaultProps'
import CustomFieldsMixin from '@/mixins/CustomFields'
import { debounce } from 'throttle-debounce'
import CrmCreateMixin from '@/mixins/CrmCreateMixin'
import { objDeepCopy } from '@/utils'
import { isEmpty } from '@/utils/types'

export default {
  // 新建编辑
  name: 'ContractCreate',

  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    XhProduct: () => import('../product/components/XhProduct'),
    WkFormItems,
    WkAfNewApply
    // WkApprovalFlowApply
  },

  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin, CrmCreateMixin],

  props: {
    action: {
      type: Object,
      default: () => {
        return {
          type: 'save',
          id: '',
          data: {}
        }
      }
    },
    examineInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},
      hasProductField: false, // 如果没有产品字段不发起产品相关请求

      // 审批信息
      flowRemarks: '',
      wkFlowList: null, // 有值有审批流
      approverEditAuth: false, // 固定审批人是否可修改
      carbonCopyEditAuth: false // 固定抄送人是否可修改
    }
  },

  computed: {
    title() {
      if (this.config.title) return this.config.title

      if (this.action.title) {
        return this.action.title
      }
      return this.action.type === 'update' ? this.$t('crm.contract.adb6269f5c0c08b4e4f4b93fca7b478c') : this.$t('crm.contract.7bcbef12d030c34741514f6cb5a27f3d')
    },

    // 确认名称
    sureBtnTitle() {
      if (this.wkFlowList) {
        return this.$t('crm.contract.9c85f5e1cf0e70c25057643a72e36b5d')
      }
      return this.$t('crm.contract.e999c75f00aa1fd6c28e6252cdd3e5ec')
    }
  },

  watch: {},

  created() {
    this.debouncedSaveField = debounce(300, this.saveClick)

    if (this.config.getFields) {
      this.getCustomField()
    } else {
      this.getField()
    }
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      this.loading = true
      const params = {
        label: crmTypeModel.contract
      }

      if (this.action.type == 'update') {
        params.id = this.action.id
      }

      filedGetFieldAPI(params)
        .then(async res => {
          const list = res.data || []

          const baseFields = []
          const fieldList = []
          const fieldForm = {}
          list.forEach(children => {
            const fields = []
            children.forEach(item => {
              // 产品字段复制
              if (item.formType == 'product') {
                this.hasProductField = true
              }

              const temp = this.getFormItemDefaultProperty(item)
              temp.show = true

              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit

              // 禁止某些业务组件选择
              if (temp.formType == 'contacts' ||
                temp.formType == 'customer' ||
                temp.formType == 'business'
              ) {
                if (this.action.type == 'relative') {
                  const relativeDisInfos = {
                    contacts: { customer: true },
                    customer: { customer: true },
                    business: { customer: true, business: true }
                  }

                  // 在哪个类型下添加
                  const relativeTypeDisInfos = relativeDisInfos[this.action.crmType]
                  if (relativeTypeDisInfos) {
                  // 包含的字段值
                    temp.disabled = relativeTypeDisInfos[item.formType] || false
                  }
                } else if (this.action.type != 'update') {
                  temp.disabled = item.formType === 'business' || item.formType === 'contacts'
                }
              }

              if (temp.formType == 'field_tag') {
                temp['tagProps'] = tagProps({ params: { type: crmTypeModel.contract }})
              }

              // 处理关联
              if ((this.action.type == 'relative' || this.action.type == 'update') && (item.formType == 'business' || item.formType == 'contacts' || item.formType == 'contract'
              )) {
                const customerObj = this.getItemRelatveInfo(list, 'customer')
                if (customerObj) {
                  if (item.formType == 'business' || item.formType == 'contacts') {
                    temp.props = {
                      params: {
                        searchList: [
                          { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] }
                        ]
                      }
                    }
                  } else if (item.formType == 'contract') {
                    temp.props = {
                      params: {
                        searchList: [
                          { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                          { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                        ]
                      }
                    }
                  }
                }
              }
              // 特殊字段允许多选
              this.getItemRadio(item, temp)

              // 获取默认值
              // 非编辑情况下 填充默认值
              if (temp.show) {
                if (this.action.type != 'update' && item.fieldName === 'orderDate') {
                  fieldForm[temp.field] = this.$moment().format('YYYY-MM-DD')
                } else {
                  fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
                }
              }

              // 复制合同时，不复制自定义编号类型的字段
              if (this.action.isCopy && temp.formType === 'serial_number') {
                fieldForm[temp.field] = null
              }

              fields.push(temp)
              baseFields.push(item)
            })
            fieldList.push(fields)
          })
          // 填充商机关联的产品信息
          if (this.action.type == 'relative') {
            const businessData = this.action.data.business
            if (businessData) {
              if (this.hasProductField) {
                const businessResData = await this.getBusinessProduct(businessData.businessId) ?? { list: [], money: null, discountRate: null }
                console.log('businessData', businessResData)
                fieldForm.product = {
                  product: businessResData.list,
                  totalPrice: businessResData.money,
                  discountRate: businessResData.discountRate
                }
                fieldForm.money = businessResData.money || ''
              }
            }
          }

          this.baseFields = baseFields
          this.fieldList = fieldList

          const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
          this.fieldForm = result.fieldForm
          this.fieldRules = result.fieldRules

          // 审核信息
          const examineParams = {
            label: 1
          }
          if (this.examineInfo.hasOwnProperty('examineStatus') && this.examineInfo.examineStatus == 2) {
            const { recordId } = this.examineInfo
            examineParams.recordId = recordId
          }

          this.initWkFlowData({
            params: examineParams,
            fieldForm: this.fieldForm
          }, (res) => {
            const list = res.list
            list.forEach(item => {
              if (item.rangeType === 2 || item.rangeType == 3) {
                item.finalUserList = objDeepCopy(item.userList)
                item.userList = []
              }
            })

            this.wkFlowList = list
            this.flowRemarks = res.resData ? res.resData.remarks : ''

            // 固定审批人/抄送人修改权限
            const modifyPermissionType = this.examineAdvancedSetting?.modifyPermissionType
            if (isEmpty(modifyPermissionType)) {
              this.approverEditAuth = true
              this.carbonCopyEditAuth = true
            } else {
              this.approverEditAuth = !modifyPermissionType.includes(1)
              this.carbonCopyEditAuth = !modifyPermissionType.includes(2)
            }
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 自定义获取
     * @return {*}
     */
    getCustomField() {
      this.loading = true
      this.config.getFields().then(fields => {
        console.log('fields---', fields)

        const list = this.convertToTwoFields(fields)
        const baseFields = []
        const fieldList = []
        const fieldForm = {}
        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = this.getFormItemDefaultProperty(item)
            temp.show = true
            if (item.formType === 'serial_number') {
              temp.disabled = !(item.authLevel == 3) // 3是可编辑
              const setItem = temp.setting.find(obj => obj.type === 1)
              if (setItem) {
                // 优先读取字段里是否允许输入配置
                const allowedInput = setItem.allowedInput == 1
                if (allowedInput && temp.disabled) { // 如果禁止改为0
                  setItem.allowedInput = 0
                }
              }
            } else {
              const canEdit = this.getItemIsCanEdit(item, this.action.type)
              // 是否可编辑
              temp.disabled = !canEdit
            }

            // 禁止某些业务组件选择
            // if (temp.formType == 'contacts' ||
            //   temp.formType == 'customer' ||
            //   temp.formType == 'business'
            // ) {
            //   if (this.action.type == 'relative') {
            //     const relativeDisInfos = {
            //       contacts: { customer: true },
            //       customer: { customer: true },
            //       business: { customer: true, business: true }
            //     }

            //     // 在哪个类型下添加
            //     const relativeTypeDisInfos = relativeDisInfos[this.action.crmType]
            //     if (relativeTypeDisInfos) {
            //     // 包含的字段值
            //       temp.disabled = relativeTypeDisInfos[item.formType] || false
            //     }
            //   } else if (this.action.type != 'update') {
            //     temp.disabled = item.formType === 'business' || item.formType === 'contacts'
            //   }
            // }

            if (temp.formType == 'field_tag') {
              temp['tagProps'] = tagProps({ params: { type: crmTypeModel.contract }})
            }

            // 处理关联
            if ((this.action.type == 'relative' || this.action.type == 'update') && (item.formType == 'business' || item.formType == 'contacts' || item.formType == 'contract'
            )) {
              const customerObj = this.getItemRelatveInfo(list, 'customer')
              if (customerObj) {
                if (item.formType == 'business' || item.formType == 'contacts') {
                  temp.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] }
                      ]
                    }
                  }
                } else if (item.formType == 'contract') {
                  temp.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'customer_id', type: 1, values: [customerObj.customerId] },
                        { formType: 'checkStatus', name: 'checkStatus', type: 1, values: [1, 10] }
                      ]
                    }
                  }
                }
              }
            }
            // 特殊字段允许多选
            this.getItemRadio(item, temp)

            // 获取默认值
            // 非编辑情况下 填充默认值
            if (temp.show) {
              if (this.action.type != 'update' && item.fieldName === 'orderDate') {
                fieldForm[temp.field] = this.$moment().format('YYYY-MM-DD')
              } else {
                fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
              }
            }

            // 复制合同时，不复制自定义编号类型的字段
            if (this.action.isCopy && temp.formType === 'serial_number') {
              fieldForm[temp.field] = null
            }

            fields.push(temp)
            baseFields.push(item)
          })
          fieldList.push(fields)
        })

        // 填充商机关联的产品信息
        // if (this.action.type == 'relative') {
        //   const businessData = this.action.data.business
        //   if (businessData) {
        //     this.getBusinessProduct(businessData.businessId).then(resData => {
        //       const businessData = resData || {}
        //       fieldForm.product = {
        //         product: businessData.list,
        //         totalPrice: businessData.money,
        //         discountRate: businessData.discountRate
        //       }
        //       fieldForm.money = businessData.money || ''
        //     }).catch(() => {})
        //   }
        // }

        this.baseFields = baseFields
        this.fieldList = fieldList

        const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
        this.fieldForm = result.fieldForm
        this.fieldRules = result.fieldRules

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 保存
     */
    saveClick(isDraft = false) {
      this.loading = true
      const crmForm = this.$refs.crmForm
      crmForm.validate(valid => {
        if (valid) {
          // 如果 afNewApply 说明没有开始审批流
          const wkFlowResult = this.$refs.afNewApply ? this.$refs.afNewApply.getParams() : {
            pass: true,
            flowParams: { list: [] }
          }
          if (wkFlowResult.pass || isDraft) {
            const params = this.getSubmiteParams([].concat.apply([], this.fieldList), this.fieldForm)
            if (isDraft) {
              params.entity.checkStatus = 5
            }

            // 审批流
            const dataMap = this.getWkFlowDataMap(this.fieldForm, wkFlowResult.flowParams.paramsData?.userFieldNames)
            params.examineFlowData = {
              label: this.examineAdvancedSetting.label,
              dataMap,
              flowDataList: wkFlowResult.flowParams.list
            }

            this.submiteParams(params)
          } else {
            this.loading = false
            this.$message.error(this.$t('crm.contract.9627574ff6b8263c6a4896c3db0b9bc1'))
          }
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(crmForm)
          return false
        }
      })
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == 'update' && !this.action.isCopy) {
        params.entity.contractId = this.action.id
        params.entity.batchId = this.action.batchId
      }

      if (params.product) {
        for (const item of params.product) {
          if (item.discount === undefined) {
            item.discount = 0
          }
          if (item.num === undefined) {
            item.num = 0
          }
          if (item.salesPrice === undefined) {
            item.salesPrice = 0
          }
          if (item.subtotal === undefined) {
            item.subtotal = 0
          }
        }
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData }
      }

      crmContractSaveAPI(params)
        .then(res => {
          this.loading = false
          if (this.action.isCopy) {
            this.$message.success(this.$t('crm.contract.e0815755a6961621338e3259e3e936de'))
          } else {
            this.$message.success(
              this.action.type == 'update' ? this.$t('crm.contract.f19434ae4760a9132bd25993b3616eda') : this.$t('crm.contract.6e825b93efcc84ae479c247778db3f8f')
            )
          }

          this.close()

          // 保存成功
          this.$emit('save-success', {
            type: 'contract'
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action)
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      // 审批流逻辑
      // this.debouncedGetWkFlowList(field.field, this.fieldForm)

      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      if (field.formType === 'customer') {
        let contractForCount = 0
        for (let mainIndex = 0; mainIndex < this.fieldList.length; mainIndex++) {
          const children = this.fieldList[mainIndex]
          for (let index = 0; index < children.length; index++) {
            const element = children[index]
            // 需要处理 需关联客户信息或客户下信息
            const handleFields = [
              'businessId',
              'contactsId',
              'companyUserId'
            ]

            // 添加请求关联
            const addRelation = ['businessId', 'contactsId']

            // 需要disabled
            const addDisabled = ['businessId', 'contactsId']

            // 复制
            const getValueObj = {
              contactsId: data => {
                if (!data.contactsId) {
                  return []
                }
                return [
                  {
                    name: data.contactsName || '',
                    contactsId: data.contactsId
                  }
                ]
              },
              companyUserId: data => {
                if (!data.ownerUserId) {
                  return []
                }
                return [
                  {
                    realname: data.ownerUserName || '',
                    userId: data.ownerUserId
                  }
                ]
              }
            }

            if (handleFields.includes(element.field)) {
              if (data.value.length > 0) {
                element.disabled = false

                // 增加关联信息
                const customerItem = data.value[0]
                if (addRelation.includes(element.field)) {
                  element.props = {
                    params: {
                      searchList: [
                        { formType: 'text', name: 'customer_id', type: 1, values: [customerItem.customerId] }
                      ]
                    }
                  }
                }

                // 填充值
                if (getValueObj[element.field]) {
                  this.fieldForm[element.field] = getValueObj[element.field](customerItem)
                } else {
                  this.fieldForm[element.field] = []
                }
              } else {
              // 禁用
                element.disabled = !!addDisabled.includes(element.field)

                if (addRelation.includes(element.field)) {
                  element.props = null
                }

                this.fieldForm[element.field] = []
              }

              contractForCount++
              if (contractForCount == handleFields.length) {
                break
              }
            }
          }
        }

        // 客户选择当从没有切换到有的时候，不进行数据重置
        const oldValue = this.fieldForm[field.field]
        if (oldValue && oldValue.length > 0) {
          // 重置产品信息
          this.fieldForm.product = {
            product: [],
            totalPrice: '',
            discountRate: ''
          }
          this.fieldForm.money = ''
          // this.debouncedGetWkFlowList('money', this.fieldForm)
        }
      } else if (field.formType === 'business') {
        if (data.value.length > 0) {
          if (this.hasProductField) {
            this.getBusinessProduct(data.value[0].businessId).then(resData => {
              const businessData = resData || {}
              this.fieldForm.product = {
                product: businessData.list || [],
                totalPrice: businessData.money,
                discountRate: businessData.discountRate
              }
              this.fieldForm.money = businessData.money || ''
            // this.debouncedGetWkFlowList('money', this.fieldForm)
            }).catch(() => {})
          }
        }
      } else if (field.formType === 'product') {
        this.fieldForm.money = data.value.totalPrice || ''
        // this.debouncedGetWkFlowList('money', this.fieldForm)
      }
      this.$set(this.fieldForm, field.field, data.value)
      this.$refs.crmForm.validateField(field.field)
    },

    /**
     * 获取商机的产品信息进行填充
     */
    getBusinessProduct(businessId) {
      return new Promise((resolve, reject) => {
        crmBusinessProductAPI({
          businessId: businessId,
          pageType: 0
        })
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    /**
     * 关闭
     */
    close() {
      this.$emit('close')
    }

  }
}
</script>

<style lang="scss" scoped>
.wk-form {
  ::v-deep .el-form-item.is-product {
    flex: 0 0 100%;
    width: 0;
  }
}
</style>
